import random


from django_redis import get_redis_connection

# Create your views here.
from rest_framework import status
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView, ListAPIView
from rest_framework.permissions import IsAuthenticated

from rest_framework.response import Response
from rest_framework.views import APIView

from celery_tasks.send_sms.tasks import send_sms_code
# from mlh.settings.dev import FDFS_URL
from mlh.utils import constants
# from question.models import Respond, Troubles
from question.models import Troubles
from users import serializers

from users.models import User
from users.serializers import UserAnswerserializer, AvatarSerializer, UserQuestionsserializer, UserPWDSerializer, \
    UserArchivesserializer


class SMSCodeView(APIView):
    """获取短信验证码"""

    def get(self, request, mobile):
        # 校验手机号是否在60秒内发送过请求
        redis_conn = get_redis_connection("verify_code")
        record_mobile = redis_conn.get("record_%s" % mobile)
        if record_mobile:
            return Response({'message': '请求次数过于频繁'})

        # 生成短信验证码
        sms_code = "%06d" % random.randint(0, 999999)
        print(sms_code)

        # 保存到redis
        # 保存真实验证
        redis_conn.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        # 保存发送记录
        redis_conn.setex("record_%s" % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)

        # 异步发送短信
        expires = str(constants.SMS_CODE_REDIS_EXPIRES // 60)
        send_sms_code.delay(mobile, sms_code, expires, 1)

        # 返回响应
        return Response({'message': 'OK'})


class UserNameView(APIView):
    """用户名验证接口"""

    def get(self, request, username):

        count = User.objects.filter(username=username).count()

        return Response({'username': username, 'count': count})


class UserMobileView(APIView):
    """手机号验证接口"""

    def get(self, request, mobile):

        count = User.objects.filter(mobile=mobile).count()

        return Response({'username': mobile, 'count': count})


class UserView(CreateAPIView):
    """
    用户注册接口
    url: users/
    """
    serializer_class = serializers.CreateUserSerializer  # 指定使用的序列化器


class UserDetailView(RetrieveAPIView):
    """
    用户详情
    """
    permission_classes = [IsAuthenticated]  # update_time声明权限-->只有通过认证的用户可以访问

    def get(self, request, *args, **kwargs):
        user = request.user

        serializer = serializers.UserDetailSerializer(user)

        return Response(serializer.data, status=status.HTTP_200_OK)


class UserCityViewSet(APIView):
    """用户现居城市"""

    permissions = [IsAuthenticated]

    def get(self, request):

        user = self.request.user
        city = user.city

        return Response({'city': city})

    def put(self, request):
        city = request.data['city']
        user = self.request.user
        user.city = city
        user.save()

        return Response({'city': city})


class UserSchool(APIView):
    """用户毕业学校"""

    permissions = [IsAuthenticated]

    def put(self, request):
        user = self.request.user
        user.school = request.data['school']
        user.specialities = request.data['specialities']

        user.save()

        return Response({'school': user.school, 'specialities': user.specialities})


class UserCompany(APIView):
    """所在公司"""
    permissions = [IsAuthenticated]

    def put(self, request):
        user = request.user
        user.company = request.data['company']
        user.position = request.data['position']

        user.save()

        return Response({'company': user.company, 'position': user.position})


class UserWeb(APIView):
    """个人网站"""
    permissions = [IsAuthenticated]

    def put(self, request):
        user = request.user
        user.website = request.data['website']

        user.save()

        return Response({'website': user.website})


class UserIntro(APIView):
    """个人简介"""
    permissions = [IsAuthenticated]

    def put(self, request):
        user = request.user
        user.intro = request.data['intro']

        user.save()
        return Response({'intro': user.intro})

# from fdfs_client.client import Fdfs_client


class UserAvatar(APIView):
    """用户头像"""
    permissions = [IsAuthenticated]

    def post(self, request):
        user = request.user

        avatar_file = request.data['file']

        serializer = AvatarSerializer(data=avatar_file)
        image = serializer.root.initial_data

        user.avatar = image
        user.save()

        serializer = AvatarSerializer(user)
        print(serializer.data)

        return Response(serializer.data, status=status.HTTP_201_CREATED)


class UserArchives(RetrieveAPIView):
    """个人档案"""
    permission_classes = [IsAuthenticated]
    serializer_class = UserArchivesserializer

    def get_object(self):
        return self.request.user.archives_set()


class MyQuestions(ListAPIView):
    """问题"""
    permission_classes = [IsAuthenticated]
    serializer_class = UserQuestionsserializer

    def get_queryset(self):
        return self.request.user.user_troubles.all()

    def get_object(self):
        return self.request.user


class MyAnswers(ListAPIView):
    """回答"""
    permission_classes = [IsAuthenticated]
    serializer_class = UserAnswerserializer

    def get_queryset(self):
        return Troubles.objects.filter(id__in=self.request.user.user_respond.only('question_id'))

# --------------------------------------------- #


from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import UpdateModelMixin

from .serializers import UserDataSerializer


class UserDataView(UpdateModelMixin, GenericViewSet):
    """用户资料修改接口"""
    permission_classes = [IsAuthenticated]
    serializer_class = UserDataSerializer

    def get_object(self):
        return self.request.user


class USerPWDView(UpdateAPIView):
    """修改密码接口"""
    permission_classes = [IsAuthenticated]
    serializer_class = UserPWDSerializer

    def get_object(self):
        return self.request.user
